package com.itcast.codec.obj.server.decoder;

import com.itcast.codec.obj.domain.User;
import com.itcast.codec.obj.util.HessianSerializerUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-23 08:52
 **/
public class HessianDecoder extends ByteToMessageDecoder {
    private HessianSerializerUtil serializerUtil = new HessianSerializerUtil();
    
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext,
                          ByteBuf in, List<Object> list) throws Exception {
        //复制一份ByteBuf数据,轻复制,非完全拷贝
        ////避免出现异常： did not read anything but decoded a message 
        // netty检查没有任何读取字节会抛出异常
        ByteBuf in2 = in.retainedDuplicate();
        
        byte[] dst;
        if (in2.hasArray()) {
            dst = in2.array();
        } else {
            dst = new byte[in2.readableBytes()];
            in2.getBytes(in2.readerIndex(), dst);
        }
        
        //跳过所有字节,表示已经度去过
        in.skipBytes(in.readableBytes());
        
        //反序列化
        Object user = serializerUtil.deserialize(dst, User.class);
        list.add(user);
    }
}
